// web/src/app/api/(learn)/course/[courseId]/chapters/[chapterId]/route.ts
// import Mux from '@mux/mux-node'
import {NextRequest, NextResponse} from "next/server";
import {currentUser} from "@/lib/auth";
import {db} from "@/lib/db";

// const {video} = new Mux({
//     tokenId: process.env.MUX_TOKEN_ID!,
//     tokenSecret: process.env.MUX_TOKEN_SECRET!,
// })


export async function PATCH(
    req: NextRequest,
    {params}: { params: { courseId: string; chapterId: string } }
) {
    try {
        const user = await currentUser()
        if (!user) return new NextResponse('Unauthorized', {status: 401})

        // 提取出isPublished, 防止意外更新
        const {isPublished, ...values} = await req.json()

        const courseOwner = await db.course.findUnique({
            where: {
                id: params.courseId,
                userId: user.id
            }
        })

        if (!courseOwner) {
            return new NextResponse('Unauthorized', {status: 401})
        }

        const chapter = await db.chapter.update({
            where: {
                id: params.chapterId,
                courseId: params.courseId,
            },
            data: {
                ...values,
            }
        })

        // if (values.videoUrl) {
        // const existingVideo = await db.muxData.findFirst({
        //     where: {
        //         chapterId: params.chapterId,
        //     }
        // })

        // if (existingVideo) {
        //     await video.assets.delete(existingVideo.assetId)
        //     await db.muxData.delete({
        //         where: {
        //             id: existingVideo.id,
        //         }
        //     })
        // }
        //
        // const asset = await video.assets.create({
        //     input: values.videoUrl,
        //     playback_policy: ['public'],
        //     test: false
        // })

        // await db.muxData.create({
        //     data: {
        //         chapterId: params.chapterId,
        //         // assetId: asset.id,
        //         // playbackId: asset.playback_ids?.[0]?.id,
        //         assetId: values.videoUrl,
        //         playbackId: values.videoUrl,
        //     }
        // })
        // }

        return NextResponse.json(chapter)
    } catch (e) {
        console.error('[COURSES_CHAPTER_ID]', e)
        return new NextResponse('Internal Server Error', {status: 500})
    }
}

export async function DELETE(
    req: NextRequest,
    {params}: { params: { courseId: string; chapterId: string } }
) {
    try {
        const user = await currentUser()
        if (!user) return new NextResponse('Unauthorized', {status: 401})

        const courseOwner = await db.course.findUnique({
            where: {
                id: params.courseId,
                userId: user.id
            }
        })

        if (!courseOwner) {
            return new NextResponse('Unauthorized', {status: 401})
        }

        const chapter = await db.chapter.findUnique({
            where: {
                id: params.chapterId,
                courseId: params.courseId,
            }
        })

        if (!chapter) return new NextResponse('Not Found', {status: 404})

        if (chapter.videoUrl) {
            // delete muxData
        }

        const deletedChapter = await db.chapter.delete({
            where: {
                id: params.chapterId,
            }
        })

        // 当前没有发布过的chapter
        const publishedChaptersInCourse = await db.chapter.findMany({
            where: {
                courseId: params.courseId,
                isPublished: true
            }
        })

        // 则课程设置为非公开
        if (!publishedChaptersInCourse.length) {
            await db.course.update({
                where: {
                    id: params.courseId
                },
                data: {
                    isPublished: false
                }
            })
        }

        return NextResponse.json(deletedChapter)
    } catch (e) {
        console.error('[COURSES_CHAPTER_ID]', e)
        return new NextResponse('Internal Server Error', {status: 500})
    }
}